package se.com.movie.reader.reader;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import se.com.movie.reader.model.Settings;
import se.com.movie.reader.xml.XmlUtil;

public class LoadXMLSettings implements Reader {
	private Settings mSettings;

	public LoadXMLSettings() {
		mSettings = Settings.getInstance();
	}

	private void createDefault() {
		try {
			Document document = XmlUtil.createDocument("1.0", "UTF-8");
			Element root = XmlUtil.createRoot(document, "settings");
			Element output = XmlUtil.addElement(root, "target");
			output.setTextContent(Settings.DEFAULT_TARGET_FILE);
			appendextensions(root);
			XmlUtil.createFile(document, Settings.SETTINGS_FILE);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

	private void appendextensions(Element root) {
		Element extensions = XmlUtil.addElement(root, "extensions");
		for (String extension : Settings.DEFAULT_FILE_EXTIONSIONS) {
			Element extensionElement = XmlUtil.addElement(extensions, "extension");
			extensionElement.setTextContent(extension);
		}
	}

	@Override
	public void read() {
		File file = new File(Settings.SETTINGS_FILE);
		if (!file.isFile()) {
			createDefault();
		}
		traverse();
	}

	private void traverse() {
		try {
			Document document = XmlUtil.readDocument(Settings.SETTINGS_FILE);
			Element root = XmlUtil.getRootElement(document);
			readOutput(root);
			readExtensions(root);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readOutput(Element root) {
		try {
			Element output = XmlUtil.getElement(root, "target");
			Settings.OUTPUT_FILENAME = XmlUtil.getValue(output);
		} catch (Exception e) {
			Settings.OUTPUT_FILENAME = Settings.DEFAULT_TARGET_FILE;
		}
	}

	private void readExtensions(Element root) {
		int count = 0;
		try {
			Element element = XmlUtil.getElement(root, "extensions");
			List<Element> extension = XmlUtil.getChildsWithName(element, "extension");
			for (Element extensionElement : extension) {
				try {
					mSettings.addExtension(XmlUtil.getValue(extensionElement).toLowerCase());
					++count;
				} catch (Exception e) {
				}
			}
		} catch (Exception e) {
		} finally {
			if (count == 0) {
				loadDefaultExtensions();
			}
		}
	}

	private void loadDefaultExtensions() {
		for (String extension : Settings.DEFAULT_FILE_EXTIONSIONS) {
			mSettings.addExtension(extension);
		}
	}
}
